package org.luckystrophe.snowtoms.model.impl;

import org.json.JSONException;
import org.json.JSONObject;
import org.luckystrophe.snowtoms.R;
import org.luckystrophe.snowtoms.model.JsonRequestPOST;
import org.luckystrophe.snowtoms.pref.UserPreference_;

import android.content.Context;

import com.googlecode.androidannotations.annotations.EBean;
import com.googlecode.androidannotations.annotations.RootContext;
import com.googlecode.androidannotations.annotations.res.StringRes;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;

@EBean
public class LoginPost extends JsonRequestPOST {

	@RootContext
	Context context;

	@Pref
	UserPreference_ pref;

	@StringRes(R.string.api_method_login)
	String apiMethod;

	@Override
	public JSONObject getBody() throws JSONException {
		JSONObject jo = new JSONObject();
		JSONObject params = new JSONObject();

		params.put("authCode", pref.snowtomsAuthcode().get());
		params.put("usrId", pref.collaboId().get());
		params.put("name", pref.name().get());
		params.put("type", "fb");

		jo.put("method", apiMethod);
		jo.put("params", params);
		return jo;
	}

	public void getAuthcode(JSONObject jo) {
		if (jo == null) {
			return;
		}
		try {
			int resultCode = jo.getInt("resultCode");

			if (resultCode != 1) {
				return;
			}

			JSONObject paramsJo = jo.getJSONObject("params");
			JSONObject paramUser = paramsJo.getJSONObject("user");

			if (paramUser.has("id")) {
				long usrId = paramUser.getLong("id");
				pref.usrId().put(usrId);
			}

			if (paramsJo.has("authCode")) {
				String authCode = paramsJo.getString("authCode");
				pref.snowtomsAuthcode().put(authCode);

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
